from application import db
from flask import current_app
from sqlalchemy import *
import datetime
import config
from common.Secret import make_uuid
import hashlib
import qrcode,base64
from io import BytesIO
from jwt import encode
class FrontUser(db.Model):
    __tablename__ = 'front_user'

    id = db.Column(Integer, primary_key=True, autoincrement=True, doc='用户主键')
    nick_name = db.Column(String(length=50), nullable=False,default='暂无昵称', doc='用户昵称')
    login_name = db.Column(String(length=64), nullable=False, unique=True, doc='登陆名')
    login_pwd = db.Column(String(length=128), nullable=False, doc='用户登陆密码')
    login_slot = db.Column(String(length=128), nullable=False)
    avatar = db.Column(String(length=128), nullable=False,default='/static/img/default_male.png', doc='用户头像')
    sex = db.Column(Integer, default=1, nullable=False, doc='用户性别 1男 2女')
    area = db.Column(String(length=128), default='暂无地区',nullable=False, doc='用户的所属地区')
    wx_number = db.Column(String(length=128), nullable=False, default='', doc='用户的微信账号')
    create_time = db.Column(DateTime, nullable=False,default=datetime.datetime.now, doc='注册时间')
    update_time = db.Column(DateTime, nullable=False, default=datetime.datetime.now, onupdate=datetime.datetime.now, doc='修改时间')
    status = db.Column(Integer, nullable=False,default=1, doc='1：用户可用，2：用户不可用')
    is_distribution = db.Column(Boolean, nullable=False,default=0, doc='1：是，0：不是')
    level= db.Column(Integer,nullable=False,default=0,doc='0 无级别 1 一级分销 2 二级分销 3 三级分销')
    commission= db.Column(DECIMAL(10,2),nullable=False,doc='佣金')

    def __init__(self, *args, **kwargs):

        if 'login_slot' not in kwargs and len(args) < 4:
            kwargs.setdefault('login_slot', make_uuid())
        super(FrontUser, self).__init__(*args, **kwargs)

    def protectPassWord(self):
        slot_str = '%s**%s' % (self.login_pwd, self.login_slot)
        md5 = hashlib.md5()
        md5.update(slot_str.encode('utf-8'))
        new_pwd = md5.hexdigest()
        self.login_pwd = new_pwd

    def checkPassWord(self, password):
        slot_str = '%s**%s' % (password, self.login_slot)
        md5 = hashlib.md5()
        md5.update(slot_str.encode('utf-8'))
        pwd = md5.hexdigest()
        if pwd == self.login_pwd:
            return True
        return False

    def __setattr__(self, key, value):
        super(FrontUser, self).__setattr__(key, value)
        if key == 'login_slot':
            self.protectPassWord()

    def get_jwt_str(self):

        jwt = encode(payload={
            'exp':datetime.datetime.utcnow() + current_app.config['JWT_EXP'],
            'user_id':self.id,
            'user_type': 'admin',
            'avatar':self.avatar,
            'nick_name':self.nick_name
        },key=current_app.config['SECRET_KEY'])

        return jwt.decode('utf-8')
    @property
    def qrcode(self):
        print(self.is_distribution)
        if self.is_distribution:
            qr = qrcode.make("%s/#/by?distribution=%s&sign=%s"%(config.DOMAIN,self.login_name,self.login_slot))
            content_header = 'data:image/png;base64,'
            Bio = BytesIO()
            qr.save(Bio)
            Bio.seek(0)
            content = base64.b64encode(Bio.read()).decode('utf-8')
            return content_header + content


class Swiper(db.Model):
    __tablename__ = 'swiper'
    id = db.Column(Integer, primary_key=True, doc='主键', autoincrement=True)
    img = db.Column(String(length=300), nullable=False, default='', doc='图片')
    link = db.Column(String(length=300), nullable=False, default='', doc='跳转')
    desc = db.Column(Text, nullable=True, default='', doc='副文本简介')


class Desc(db.Model):
    __tablename__ = 'desc'
    id = db.Column(Integer, primary_key=True, doc='主键', autoincrement=True)
    title = db.Column(String(length=300), nullable=False, default='', doc='标题')
    desc = db.Column(String(length=300), nullable=True, default='', doc='简介')


class Article(db.Model):

    __tablename__ = 'article'
    id = db.Column(Integer, primary_key=True, doc='主键', autoincrement=True)
    title = db.Column(String(length=300), nullable=False, default='', doc='标题')
    content = db.Column(Text, nullable=True, default='', doc='副文本内容')
    create_time = db.Column(DateTime, nullable=False,default=datetime.datetime.now, doc='创建时间')
    update_time = db.Column(DateTime, nullable=False, default=datetime.datetime.now, onupdate=datetime.datetime.now,
                            doc='修改时间')


class OursGoodness(db.Model):
    __tablename__ = 'goodness'
    id = db.Column(Integer, primary_key=True, doc='主键', autoincrement=True)
    content = db.Column(Text, nullable=True, default='', doc='副文本内容')
    create_time = db.Column(DateTime, nullable=False,default=datetime.datetime.now, doc='创建时间')
    update_time = db.Column(DateTime, nullable=False, default=datetime.datetime.now, onupdate=datetime.datetime.now,doc='修改时间')


class ProductExamples(db.Model):
    __tablename__ = 'examples'
    id = db.Column(Integer, primary_key=True, doc='主键', autoincrement=True)
    img = db.Column(String(length=300), nullable=False, default='', doc='图片')
    desc = db.Column(String(length=300), nullable=False, default='', doc='描述')
    create_time = db.Column(DateTime, nullable=False,default=datetime.datetime.now, doc='创建时间')
    update_time = db.Column(DateTime, nullable=False, default=datetime.datetime.now, onupdate=datetime.datetime.now,doc='修改时间')


class Product(db.Model):

    __tablename__ = 'product'
    id = db.Column(Integer, primary_key=True, doc='主键', autoincrement=True)
    img = db.Column(String(length=300), nullable=False, default='', doc='图片')
    name = db.Column(String(length=300), nullable=False, default='', doc='名称')
    desc = db.Column(String(length=300), nullable=False, default='', doc='描述')
    use = db.Column(Boolean, nullable=False, default=True, doc='是否删除')
    sale_number = db.Column(Integer, nullable=False, default=0, doc='售卖数量')
    create_time = db.Column(DateTime, nullable=False,default=datetime.datetime.now, doc='创建时间')
    update_time = db.Column(DateTime, nullable=False, default=datetime.datetime.now, onupdate=datetime.datetime.now,
                            doc='修改时间')


class ProductType(db.Model):

    id = db.Column(Integer, primary_key=True, doc='主键', autoincrement=True)
    name = db.Column(String(length=300), nullable=False, default='', doc='图片')
    desc = db.Column(String(length=300), nullable=False, default='', doc='描述')
    price = db.Column(DECIMAL(10,2), nullable=False, default=0.0, doc='价格')
    type = db.Column(Integer, nullable=False, default=1, doc='1 清理好友，2群发')
    f_limit = db.Column(Integer, nullable=False, default=100, doc='检测好友的数量')
    product_id = db.Column(Integer, ForeignKey(Product.id, ondelete='RESTRICT'), doc='主键')
    product = db.relationship(Product, backref=db.backref('types'))

    def __eq__(self, el):
        assert isinstance(el, ProductType), Exception(
            'can\'t equals ProductType and %s' % (type(el)))
        
        return self.name == el.name and \
            self.desc == el.desc and \
            float(self.price) == float(el.price) and \
            self.f_limit == el.f_limit and \
                self.type == el.type
    
    def update(self,name,desc,price):

        self.name = name
        self.desc = desc
        self.price = price



class Tutorials(db.Model):

    __tablename__ = 'tutorials'

    id = db.Column(Integer,primary_key=True,autoincrement=True)
    video = db.Column(String(length=300), nullable=False, default='', doc='视频地址')
    desc = db.Column(String(length=300), nullable=False, default='', doc='描述')
    create_time = db.Column(DateTime, nullable=False,default=datetime.datetime.now, doc='创建时间')
    update_time = db.Column(DateTime, nullable=False, default=datetime.datetime.now, onupdate=datetime.datetime.now,doc='修改时间')


class Distribution(db.Model):
    __tablename__ = 'distribution'
    id = db.Column(Integer, primary_key=True, doc='主键', autoincrement=True)
    pay_number = db.Column(DECIMAL(10,2),nullable=False,doc='订单金额')
    level = db.Column(Integer,nullable=False,default=0,doc='0 无级别 1 一级分销 2 二级分销 3 三级分销')
    pay_channels = db.Column(Integer,nullable=False,default=1,doc='1 微信，2支付宝，，支付渠道')
    is_pay  = db.Column(Boolean,nullable=False,default=False,doc='是否支付')
    order_number = db.Column(String(length=300),nullable=False,default=make_uuid,doc='订单号')
    pay_time = db.Column(DateTime,nullable=True,doc='支付时间')
    trade_no = db.Column(String(length=300),nullable=True,default=make_uuid,doc='支付宝或者微信订单号')
    user_id = db.Column(Integer, ForeignKey(FrontUser.id, ondelete='RESTRICT'), doc='主键')
    user = db.relationship(FrontUser, backref=db.backref('DistributionOrder'))


class TransferHistory(db.Model):
    __tablename__ = 'transfer_history'

    id = db.Column(Integer,primary_key=True,autoincrement=True)
    create_time = db.Column(DateTime,nullable=False,default=datetime.datetime.now)
    update_time = db.Column(DateTime,nullable=False,default=datetime.datetime.now,onupdate=datetime.datetime.now)
    transfer_number = db.Column(DECIMAL(10,2),nullable=False,doc='订单金额')
    transfer_channels = db.Column(Integer,nullable=False,default=1,doc='1 微信，2支付宝，，支付渠道')
    is_transfer  = db.Column(Boolean,nullable=False,default=False,doc='是否支付')
    transfer_id = db.Column(String(length=300),nullable=False,default=make_uuid,doc='订单号')
    alipay_account = db.Column(String(length=300),nullable=False,default='',doc='支付宝帐号')
    transfer_time = db.Column(DateTime,nullable=True,doc='支付时间')
    trade_no = db.Column(String(length=300),nullable=True,default=make_uuid,doc='支付宝或者微信订单号')
    user_id = db.Column(Integer,db.ForeignKey(FrontUser.id, ondelete='RESTRICT'),nullable=True,doc='用户')
    user = db.relationship(FrontUser,backref=db.backref('TransferHistorys',uselist=False),cascade='all')